package log

import (
	"fmt"
	"github.com/cloudwego/hertz/pkg/common/hlog"
	hertzlogrus "github.com/hertz-contrib/logger/logrus"
	"github.com/sirupsen/logrus"
	"gopkg.in/natefinch/lumberjack.v2"
	"io"
	"log"
	"login/src/conf"
	"os"
	"path"
	"time"
)

var logLevel = map[string]hlog.Level{
	"Trace":  hlog.LevelTrace,
	"Debug":  hlog.LevelDebug,
	"Info":   hlog.LevelInfo,
	"Notice": hlog.LevelNotice,
	"Warn":   hlog.LevelWarn,
	"Error":  hlog.LevelError,
	"Fatal":  hlog.LevelFatal,
}

var _ *logrus.Logger

func Init() {
	var logFilePath string
	timeStr := time.Now().Format("2006-01-02")
	logFilePath = conf.GetConf().Log.Dir + fmt.Sprintf("/%s/", timeStr)
	if err := os.MkdirAll(logFilePath, 0o777); err != nil {
		log.Println(err.Error())
		return
	}

	// 将文件名设置为日期
	logFileName := timeStr + ".log"
	fileName := path.Join(logFilePath, logFileName)
	if _, err := os.Stat(fileName); err != nil {
		if _, err := os.Create(fileName); err != nil {
			log.Println(err.Error())
			return
		}
	}

	logger := hertzlogrus.NewLogger()
	// 提供压缩和删除
	lumberjackLogger := &lumberjack.Logger{
		Filename:   fileName,
		MaxSize:    20,   // 一个文件最大可达 20M。
		MaxBackups: 5,    // 最多同时保存 5 个文件。
		MaxAge:     10,   // 一个文件最多可以保存 10 天。
		Compress:   true, // 用 gzip 压缩。
	}

	logger.SetOutput(lumberjackLogger)
	logger.SetLevel(logLevel[conf.GetConf().Log.Level])
	logger.Logger().SetFormatter(
		&logrus.TextFormatter{
			ForceColors:               true,
			ForceQuote:                true,
			FullTimestamp:             true,
			EnvironmentOverrideColors: true,
		})

	fileWriter := io.MultiWriter(lumberjackLogger, os.Stdout)
	logger.SetOutput(fileWriter)

	hlog.SetLogger(logger)
}

// 获取目录名称
func getDirName(path string) string {
	return path[0 : len(path)-len(fileName(path))]
}

func fileName(path string) string {
	for i := len(path) - 1; i >= 0; i-- {
		if os.IsPathSeparator(path[i]) {
			return path[i+1:]
		}
	}
	return path
}
